'use strict';

const Controller = require('egg').Controller;
const md5 = require('md5')

class UpdateuserController extends Controller {
  async updateUser() {
    const { ctx, app } = this
    const {id, action} = ctx.request.body
    // 禁用账号
    if (action === 'disable') {
      const row = {
        id,
        account_status: 0,
        updated_at: app.mysql.literals.now
      }
      const result = await ctx.service.user.updateUser(row)
      if (result.affectedRows === 1) {
        ctx.body = {
          code: 1,
          msg: '更新成功'
        }
      } else {
        ctx.body = {
          code: 0,
          msg: '更新失败'
        }
      }
      return
    }

    // 启用账号
    if (action === 'enable') {
      const row = {
        id,
        account_status: 1,
        updated_at: app.mysql.literals.now
      }
      const result = await ctx.service.user.updateUser(row)
      if (result.affectedRows === 1) {
        ctx.body = {
          code: 1,
          msg: '更新成功'
        }
      } else {
        ctx.body = {
          code: 0,
          msg: '更新失败'
        }
      }
      return
    }

    // 重置密码
    if (action === 'resetPassword') {
      const row = {
        id,
        password: md5('123456')
      }
      const result = await ctx.service.user.updateUser(row)
      if (result.affectedRows === 1) {
        ctx.body = {
          code: 1,
          msg: '更新成功'
        }
      } else {
        ctx.body = {
          code: 0,
          msg: '更新失败'
        }
      }
      return
    }
    
  }
}

module.exports = UpdateuserController;
